// 封装请求
import { ElMessage } from 'element-plus'


export interface ResponseConfig {
  code: number,
  status: number,
  data: any,
  message: string
}
export interface ValueConfig {
  value: any,
}

let reqUrl: string

const fetch = (url: string, options?: any): Promise<any> => {
    const headers = { 
      "Content-Type": "application/json;charset=utf-8",
      'X-Requested-With': 'XMLHttpRequest',
      'Access-Control-Allow-Origin': '*'
    }
    const api = 'http://8.137.150.77:3302/'
    const localhost = 'http://localhost:8000/'
    reqUrl = api + url
    return new Promise((resolve, reject) => {
      useFetch(reqUrl, { ...options, headers }).then(({ data }: any) => {
        const value = data.value
          if (value.code !== 200) {
            // 这里处理错误回调
            ElMessage({
              message: value.message,
              type: 'error',
              duration: 1000,
              center: true,
            })
          }   
          else {
            resolve(ref(value))
          }
      }).catch((err: any) => {
          reject(err)
      })
    })
}

export default new class Http {

    get(url: string, params?: any): Promise<any> {      
        return fetch(url, { method: 'GET', params })
    }

    post(url: string, body?: any): Promise<any> {
        return fetch(url, { method: 'POST', body })
    }

    put(url: string, body?: any): Promise<any> {
        return fetch(url, { method: 'PUT', body })
    }

    delete(url: string, body?: any): Promise<any> {
        return fetch(url, { method: 'DELETE', body })
    }
}
